package com.ihr360.alps;

import com.google.common.collect.Maps;
import com.ihr360.alps.api.IDListWithCriteriaRequest;
import com.ihr360.alps.api.IServiceProvider;
import com.ihr360.commons.context.session.Ihr360Session;
import com.ihr360.commons.context.session.Ihr360SessionContextHolder;
import com.ihr360.commons.entity.AuthUserInfo;
import com.ihr360.commons.lang.CollectionUtils;
import com.ihr360.insurance.service.MonthlyLedgerService;
import com.ihr360.insurance.service.MonthlyLedgerSummaryService;
import com.ihr360.shared.advice.response.DisableResponseAdvice;
import com.ihr360.validation.ValidationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.Map;

@RestController
@RequestMapping("/alps/SIHF")
@DisableResponseAdvice
public class SIHFServiceProvider implements IServiceProvider<Map<String, Double>> {

    @Autowired
    private MonthlyLedgerService ledgerService;

    @Autowired
    private MonthlyLedgerSummaryService monthlyLedgerSummaryService;


    @PostMapping(value = "/{year}/{month}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Override
    public Map<String, Map<String, Double>> getItems(@RequestParam(name = "companyId") String companyId, @PathVariable(name = "year") int year, @PathVariable(name = "month") int month, @RequestBody IDListWithCriteriaRequest request) {
        String userId = getUserId();
        boolean ledgerLocked = monthlyLedgerSummaryService.isLedgerLocked(companyId, userId, year, month);
        //台账未锁定，则不返回台账数据
        if (!ledgerLocked) {
            return Maps.newHashMap();
        }
        return ledgerService.getStaffLedger(companyId, userId, year, month,
                CollectionUtils.isEmpty(request.getIds()) ? Collections.emptyList() : request.getIds());
    }

    private String getUserId() {
        Ihr360Session session = Ihr360SessionContextHolder.getSession();
        ValidationUtils.rejectIfEmpty(session, null, "当前session不存在");
        AuthUserInfo userInfo = session.getUserInfo();
        ValidationUtils.rejectIfAnyNull(null, "当前用户数据不存在", userInfo, userInfo.getUserId());
        return userInfo.getUserId();
    }

}